package com.zxb.user.controller;

import com.zxb.common.utlis.R;
import com.zxb.user.feign.OrderFeignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@Slf4j
public class UserController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RestTemplate restTemplate2;

    @Autowired
    private RestTemplate restTemplate3;

    @Autowired
    private OrderFeignService orderFeignService;

    @RequestMapping(value = "/findOrderByUserId/{id}")
    public R findOrderByUserId(@PathVariable Integer id) {

        log.info("根据userId:" + id + "查询订单信息");

        //模拟ribbon实现
        //String url = getUri("mall-order")+"/order/findOrderByUserId/"+id;
        //System.out.println(getUrl("mall-order"));
        String url = "http://mall-order/order/findOrderByUserId/" + id;

        R r = restTemplate3.getForObject(url, R.class);

        return r;
    }

    @RequestMapping(value = "/findOrderByUserIdF/{id}")
    public R findOrderByUserIdF(@PathVariable Integer id) {

        log.info("根据userId:" + id + "查询订单信息");

        R r = orderFeignService.findOrderByUserId(id);

        return r;
    }


    @Autowired
    private DiscoveryClient discoveryClient;

    private AtomicInteger nextIndex = new AtomicInteger(0);

    public String getUrl(String sericeName) {
        //获取服务的实例
        List<ServiceInstance> serviceInstances = discoveryClient.getInstances(sericeName);
        if (CollectionUtils.isEmpty(serviceInstances)) {
            return null;
        }
        int size = serviceInstances.size();
        //轮询
        int indexServer = incrementAndGetModulo(size);
        return serviceInstances.get(indexServer).getUri().toString();
    }

    private int incrementAndGetModulo(int modulo) {
        for (; ; ) {
            int current = nextIndex.get();
            int next = (current + 1) % modulo;
            if (nextIndex.compareAndSet(current, next) && current < modulo) {
                return current;
            }
        }
    }


}
